﻿using AutoMapper;
using MediatR;
using S.Services.SheepMale.Api.Application.Command.PurchaseCommand;
using S.Services.SheepMale.Domain.PurchaseSales;
using S.Services.SheepMale.Infrastructure;

namespace S.Services.SheepMale.Api.Application.CommandHandler.PurchaseCommandHandler
{
    public class PurchaseEditCommandHandler : IRequestHandler<PurchaseEditCommand, int>
    {
        private readonly IRepository<EntityPurchase> repository;

        private readonly IMapper mapper;
        public PurchaseEditCommandHandler(IRepository<EntityPurchase> repository,IMapper mapper)
        {
            this.repository = repository;
            this.mapper = mapper;
        }

        public async Task<int> Handle(PurchaseEditCommand request, CancellationToken cancellationToken)
        {
            var result = repository.AllAsync().Result.Where(x=>x.Earbugles==request.Earbugles&&x.DocumentNumber==request.DocumentNumber&&x.PurId!=request.PurId);
            if (result.Count()!=0)
            {
                return -1;
            }
            
            request.UpdateDate= DateTime.Now;
            return await repository.UpdateAsync(mapper.Map<EntityPurchase>(request));
        }
    }
}
